package com.petRescueCenter.demo.pet.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.petRescueCenter.demo.common.util.ProjectPath;
import com.petRescueCenter.demo.common.web.VueResponse;
import com.petRescueCenter.demo.common.web.VuejsPageRequest;
import com.petRescueCenter.demo.pet.entity.Pet;
import com.petRescueCenter.demo.pet.entity.dto.PetDTO;
import com.petRescueCenter.demo.pet.entity.dto.PetQueryDTO;
import com.petRescueCenter.demo.pet.service.IPetService;
import com.petRescueCenter.demo.user.service.IUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(description = "宠物相关的api")
@RestController
@RequestMapping(value = "/pet")
public class PetController {
	@Autowired
	private IPetService petService;
	@Autowired
	private IUserService userService;

	@ApiOperation(value = "查询宠物信息列表", notes = "分页返回")
	@GetMapping
	public Page<PetDTO> getAll(PetQueryDTO petQueryDTO, VuejsPageRequest pageRequest) {
		return petService.findAll(PetQueryDTO.getWhereClause(petQueryDTO), pageRequest.getPageable());
	}

	@DeleteMapping
	public VueResponse delete(Long id) {
		try {
			petService.deleteById(id);
			return new VueResponse(true, "删除成功");
		} catch (Exception e) {
			// TODO: handle exception
			return new VueResponse(false, "删除失败");
		}
	}

	@ApiOperation(value = "添加宠物信息", notes = "刚添加的宠物自动添加主人为管理者,返回的类型中狗0, 猫1,其他2;")
	@PostMapping("addImg")
	public VueResponse save(@RequestParam("file") MultipartFile file) {
		try {
			Pet pet = new Pet();
			String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

			// p1为路径，user.getName()为相片名字，fileType为类型
			String filename = UUID.randomUUID() + fileType;
			Path path = Paths.get(ProjectPath.getRootPath("static/img/pet/") + filename);
			File filePath = new File(ProjectPath.getRootPath("static/img/pet/"));
			System.out.println("文件的保存路径：" + path);
			if (!filePath.exists() && !filePath.isDirectory()) {
				System.out.println("目录不存在，创建目录:" + filePath);
				filePath.mkdir();
			}
			pet.setImg("img/pet/" + filename);// 保存到数据库的路径
			// 把获得的文件保存
			file.transferTo(path.toFile());
			pet = petService.save(pet);
			return new VueResponse(true, pet.getId().toString());
		} catch (Exception e) {
			// TODO: handle exception
			System.err.println(e);
			return new VueResponse(false, "添加失敗");
		}
	}

	@PostMapping("/add")
	public VueResponse add(PetDTO dto) {
		try {
			Pet entity = new Pet();
			dto.dtoToEntity(entity, dto);
			entity.setImg(petService.findById(dto.getId()).getImg());
			petService.save(entity);
			return new VueResponse(true, "添加成功");
		} catch (Exception e) {
			// TODO: handle exception
			System.err.println(e);
			return new VueResponse(false, "添加失敗");
		}
	}

	@PostMapping("/deleteImg")
	public VueResponse deleteImg(@RequestParam("id") Long id) {
		try {
			Pet pet = new Pet();
			pet = petService.findById(id);
			File oldFile = new File(ProjectPath.getRootPath("static/") + pet.getImg());
			if (oldFile.exists())
				oldFile.delete();
			pet.setImg(null);
			petService.save(pet);
			return new VueResponse(true, "删除图片成功");
		} catch (Exception e) { // TODO: handle exception
			return new VueResponse(false, "删除图片失败！");
		}
	}

	@GetMapping("/getOne")
	public PetDTO getOnePet(Long id) {
		Pet pet = petService.findById(id);
		PetDTO dto = new PetDTO();
		dto.entityToDto(pet, dto);
		return dto;

	}

	@ApiOperation(value = "修改宠物图像", notes = "")
	@PostMapping("/upload")
	public VueResponse fileUpload(@RequestParam("file") MultipartFile file, @RequestParam("id") Long id) {
		Pet pet = petService.findById(id);
		String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		if (fileType.equals(".jpg") || fileType.equals(".png")) {
			if (file.isEmpty()) {
				return new VueResponse(false, "没有选择有效文件！");
			}
			try {
				String filename = UUID.randomUUID() + fileType;
				Path path = Paths.get(ProjectPath.getRootPath("static/img/pet/") + filename);
				String oldImgUri = pet.getImg();
				pet.setImg("img/pet/" + filename);// 保存到数据库的路径
				// 把获得的文件保存
				file.transferTo(path.toFile());
				petService.save(pet);
				File oldfile = new File(ProjectPath.getRootPath("static/img/pet/") + oldImgUri);
				if (oldfile.exists()) {
					oldfile.delete();
				}
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("img", pet.getImg());
				map.put("msg", "上传成功！");
				return new VueResponse(true, map);
			} catch (IOException e) {
				e.printStackTrace();
				return new VueResponse(false, "上传失败！");
			}
		}
		return new VueResponse(false, "请选择jpg或png格式！");
	}

}
